<?php
namespace App\HttpController\Pay;

use EasySwoole\Core\Http\AbstractInterface\Controller;
use Yansongda\Pay\Log;
use Yansongda\Pay\Pay;
use Yansongda\Supports\Collection;
use Exception;
use App\Utility\Common;
use EasySwoole\Core\Http\Message\Status;

class AliPaySdk extends Controller
{

    protected $alipay = null;

    // 加密方式： **RSA2**
    // optional
    protected $config = [
        'app_id' => '2016091200494067',
        'notify_url' => 'http://chat.7b620.cn/Pay/AliPaySdk/notify',
        'return_url' => 'http://chat.7b620.cn/Pay/AliPaySdk/return',
        'ali_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq56wNq8PjNeNYJOfj81IHlrM7YS2ZlC7TEG8xZsgPAZG4lXRCHiwg9wyLwetTDB/8JcU8VcuhKN3ZuBj9fgqgEyE+JsRygjagzK0T83l97EJ5ycoLqzURSHu9Yi0pmc3tZg3d1oV/agYY63qTlNXZ8hKf64dRWszf5b5yhxc1MYsF6gpQ/2VNtz+X3D0zNcNMKTkGaqs/BsDeBLMlrqUOq0HJJn4nGEdCfu9wSLnuTJ/+0qHT1tQ3AnXSvN02PdqvqsuL6e+AVlJOQ3fj+jkBrXi0b89TXNekKJo3AMPvyMNTlWSj4CkzAIosgvlYWQVx4cX4CTiia1Amr6ADu3NZwIDAQAB',
        'private_key' => 'MIIEpAIBAAKCAQEAwYWEYtI1SQ4RtfxvSSjZHkOaMrppu1E1b5S4Nj9ZHzUn7aRdDah1YCC5J/PpkN1Ce0yqIsjp0hkR7ojll4BL1XZVCjPODpEcaAZXG3wTNn1Gt4EIReljE8JcFhm5A9tB69gOn2u93SK7z+n6DJ05+ypWog6JJOUkV3HITxpE1omBm74TOr1H+7ZhnpugNYjy18VgsxNNrwn6A6sqysgT/2v5WJdhIflmw3wbmG0rBZZrkV3reJmjldiLCdbhLdGFnaExsnWVrt67NPGxRu5IG/CTYIaYDbxhGUl+F/dMa39LNP+gQsJYAiMa464yAQZhWbilWlz8C4u+r5AEvACm6wID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tztXqLKMrq7IpgKDMKc5NDvbqj5bAH4b5SwDHaduHlcBxrz3Opck/kgIHTVMNrSTOIBj5GoZcTu+7ikoy2QCLs8lqviZwoCY1F8Cc1SmEbQXS68V8uBOLrV24Eoaur3fMdQgLLmWaz7A==',
        'log' => [
            'file' => './logs/alipay.log',
            'level' => 'debug'
        ],
        'mode' => 'dev' // optional,设置此参数，将进入沙箱模式
    ];

    protected function onRequest($action): ?bool
    {
        $this->alipay = Pay::alipay($this->config);
        return true;
    }

    protected function actionNotFound($action): void
    {
        $this->response()->withStatus(Status::CODE_NOT_FOUND);
    }

    private function web($order): String
    {
        return $this->alipay->web($order);
    }

    private function wap($order): String
    {
        return $this->alipay->wap($order)->send();
    }

    private function scan($order): Collection
    {
        return $this->alipay->scan($order);
    }

    public function webPay()
    {
        $order = [
            'out_trade_no' => time(),
            'total_amount' => '0.01',
            'subject' => 'test subject - 测试'
        ];
        $re = $this->web($order);
        $this->response()->write($re);
    }

    public function scanPay()
    {
        $order = [
            'out_trade_no' => time(),
            'total_amount' => '0.01',
            'subject' => 'test subject - 测试'
        ];
        $re = $this->scan($order)->toArray();
        $this->writeJson(Status::CODE_OK, $re);
    }

    public function wapPay()
    {
        $order = [
            'out_trade_no' => time(),
            'total_amount' => '0.01',
            'subject' => 'test subject - 测试'
        ];
        
        $re = $this->wap($order);
        $this->response()->write($re);
    }

    public function return()
    {
        (new Common())->E("return");
        $requestdata = $this->request()->getQueryParams();
        
        // 是的，验签就这么简单！
        // 订单号：$data->out_trade_no
        // 支付宝交易号：$data->trade_no
        // 订单总金额：$data->total_amount
        $data = $this->alipay->verify($requestdata)->toArray();
        
        var_dump($data);
    }

    public function notify()
    {
        (new Common())->E("notify");
        $requestdata = $this->request()->getRequestParam();
        try {
            // 是的，验签就这么简单！
            // 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
            // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
            // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
            // 3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）；
            // 4、验证app_id是否为该商户本身。
            // 5、其它业务逻辑情况
            $data = $this->alipay->verify($requestdata);
            var_dump($data);
            Log::debug('Alipay notify', $data->all());
        } catch (Exception $e) {
            $e->getMessage();
        }
        
        $success = $this->alipay->success()->send();
        $this->response()->write($success);
    }

    /**
     *
     * {@inheritdoc}
     *
     * @see \EasySwoole\Core\Http\AbstractInterface\Controller::index()
     */
    public function index()
    {
        // TODO Auto-generated method stub
    }
}